<template>
    <a-modal v-model:visible="visible" :unmount-on-close="true" :title="index >= 0 ? '编辑连接' : '新建连接'" draggable @cancel="handleCancel"
             @before-ok="handleOk">
        <a-form ref="formRef" :model="form">
            <a-form-item field="name" label="名称" :rules="[{required:true,message:'请输入连接名称'}]">
                <a-input v-model="form.name" placeholder="请输入连接名称"/>
            </a-form-item>
            <a-form-item field="host" label="IP" :rules="[{required:true,message:'请输入连接IP地址'}]">
                <a-input v-model="form.host" placeholder="请输入连接IP地址"/>
            </a-form-item>
            <a-form-item field="port" label="端口" :rules="[{required:true,message:'请输入连接端口'}]" tooltip="请使用REST连接器端口">
                <a-input v-model="form.port" placeholder="请输入连接端口"/>
            </a-form-item>
            <a-form-item field="username" label="用户名" :rules="[{required:true,message:'请输入用户名'}]">
                <a-input v-model="form.username" placeholder="请输入用户名"/>
            </a-form-item>
            <a-form-item field="password" label="密码" :rules="[{required:true,message:'请输入密码'}]">
                <a-input-password v-model="form.password" placeholder="请输入密码"/>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">

import {reactive, ref} from 'vue';

const visible = ref(false);

let form = reactive({
    name: "new connection",
    host: "127.0.0.1",
    port: "6041",
    username: "root",
    password: "taosdata",
    version: ""
});

const formRef = ref()

const emits = defineEmits(['done'])

let index = -1;

const add = () => {
    form = reactive({
        name: "new connection",
        host: "127.0.0.1",
        port: "6041",
        username: "root",
        password: "taosdata",
        version: ""
    })
    index = -1
    visible.value = true;
};

const edit = (connection, connectionIndex) => {
    form = reactive(connection)
    index = connectionIndex;
    visible.value = true;
};

const handleCancel = () => {
    visible.value = false;
}

const handleOk = (done) => {
    formRef.value.validate((errors) => {
        if (!errors) {
            emits('done', JSON.parse(JSON.stringify(form)), index)
            done()
        } else {
            done(false)
        }
    })
};

defineExpose({
    add, edit
})


</script>
